/**
 * 播放器
 */
let bgAudioManager;

export const createPlayer = () => {
	// #ifdef MP-WEIXIN
	bgAudioManager = uni.getBackgroundAudioManager();
	// #endif
	// #ifdef H5 || APP-PLUS
	// 没有正在播放的音乐才允许播放，防止重复播放
	if (!bgAudioManager) {
		bgAudioManager = uni.createInnerAudioContext();
	}
	// #endif
	console.log("播放器已创建",bgAudioManager);

	// 监听事件
	bgAudioManager.onStop(() => uni.$emit('onStop', bgAudioManager))

	bgAudioManager.onPlay(() => uni.$emit('onPlay', bgAudioManager))

	bgAudioManager.onPause(() => uni.$emit('onPause', bgAudioManager))

	bgAudioManager.onWaiting(() => uni.$emit('onCanplay', bgAudioManager))

	bgAudioManager.onTimeUpdate(() => uni.$emit('onTimeUpdate', bgAudioManager))

	bgAudioManager.onError(() => uni.$emit('onError', bgAudioManager))

	bgAudioManager.onEnded(() => uni.$emit('onEnded', bgAudioManager))

	// 监听系统操作中心切歌 仅IOS
	if (bgAudioManager.onPrev) {
		bgAudioManager.onPrev(() => uni.$emit('onPrev', bgAudioManager))
		bgAudioManager.onNext(() => uni.$emit('onNext', bgAudioManager))
	}
}

/**
 * 获取当前背景音乐
 */
export const getPlayer = () => {
	console.log("获取当前背景音乐",bgAudioManager);
	return bgAudioManager
}

/**
 * @param {string} data: 设置歌曲信息  并播放
 */
export const setInfo = (data) => {
	console.log("设置歌曲信息",data);
	//中止上一首
	if (bgAudioManager?.src) bgAudioManager.stop()

	if (!!uni.getBackgroundAudioManager) {
		console.log(bgAudioManager);
		bgAudioManager.title = data.title
		bgAudioManager.singer = data.artist
		bgAudioManager.epname = data.album
		bgAudioManager.coverImgUrl = data.picUrl
	} else {
		bgAudioManager.obeyMuteSwitch = true
		bgAudioManager.volume = 0.3
		bgAudioManager.playbackRate = 'playback'
	}
	bgAudioManager.src = data.url
	bgAudioManager.play()
}